<template>
    <div class="login-container">
      <el-form :model="loginForm" ref="loginFormRef" :rules="rules" label-width="80px">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="loginForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import {toast} from '@/composables/utils'
  import {login} from '@/apis/user'
  import {useRouter} from 'vue-router'
  import {useUserStore} from '@/stores/user'

  const router = useRouter()
  const userStore = useUserStore()
  
  const loginForm = ref({
    email: '',
    password: ''
  });
  
  const loginFormRef = ref(null);
  
  const rules = ref({
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ]
  });
  
  const handleLogin = () => {
    loginFormRef.value.validate((valid) => {
      if (valid) {
        // 执行登录逻辑
        login({
            email: loginForm.value.email,
            password: loginForm.value.password
        }).then(res => {
            console.log(res)
            toast('登录成功', 'success')
            // 存储token到pinia
            userStore.userInfo = res.data.userinfo

            // 跳转到首页
            router.replace('/')
        })
      } else {
        toast('请输入正确的邮箱和密码', 'error')
      }
    });
  };
  </script>
  
  <style scoped>
  .login-container {
    width: 300px;
    margin: 100px auto;
    padding: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #fff;
  }
  </style>
  